#translator.py
import sort_utils

def flattenRule(rule):
	flat = ''
	(type,head,body) = rule
	if len(body)>0:
		frule = head+[(0,' :- ')]+body
	else:
		frule = head
	for constr in frule:
		if constr[0] == 3:
			#atom
			flat = flat+constr[2]
		elif constr[0] == 0:
			#plain
			flat = flat+constr[1]
		else:
			raise Exception('Untranslated construct')
	return flat

#translates a single rule r into a new rule (as a tuple) plus auxilliary rules
def translateRule(rule, line, sortdb):
	(type, head, body) = rule
	#get decorations (head and body)
	decr = sort_utils.SortDec(rule, line, sortdb)
	hdec = decr.hdec
	bdec = decr.bdec
	#constraints of free terms
	f_constraints = ''
	for (part,dec) in [(head,hdec), (body,bdec)]:
		i = 0
		while i<len(part):
			(E,I,C) = dec[i]
			constr = part[i]
			if constr[0] == 3:
				for atom in E:
					if not atom in f_constraints:
						f_constraints = f_constraints+','+atom
			i +=1
	##...TRANSLATE aggs, quants!
	#add constraints to body
	if f_constraints:
		if len(body)>0:
			body.insert(-1,(0,f_constraints))
		else:
			stripd = (head[-1][0], head[-1][1].strip('.'))
			head[-1] = stripd
			body.append((0, f_constraints[1:]+'.'))
	trans = flattenRule(rule)
	return trans